package com.mostka.rpc.util;

import java.lang.reflect.InvocationTargetException;


public class InstanceCreator {
	@SuppressWarnings("rawtypes")
	public static Object getObjectInstance(String typeName, Object... parameters) throws Exception{
		try {
			Class cl = Class.forName(typeName);
			return getObjectInstance(cl, parameters);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new Exception();
		}
	}
	@SuppressWarnings("rawtypes")
	public static Object getObjectInstance(Class cl, Object... parameters) throws Exception{
		try {
			Class<?>[] parameterTypes = new Class<?>[parameters.length];
			for (int i=0;i<parameters.length;i++){
				parameterTypes[i]=parameters[i].getClass();
			}
			@SuppressWarnings("unchecked")
			java.lang.reflect.Constructor co = cl.getConstructor(parameterTypes);
			return co.newInstance(parameters);
		} catch (SecurityException | NoSuchMethodException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
			System.out.println("unable to create class "+cl.getCanonicalName());
			e1.printStackTrace();
			throw new Exception();
		}
	}
}
